﻿/*----------------------------------------------------------------
 * 
 * 版权所有：Copyright (C) 2013
 * 
 * 文件名：OrderByExpression.cs
 * 文件功能描述：
 * 
 * 
 * 作 者：zhangq
 * 邮 箱：ifunnyface@outlook.com
 * 日 期：2013-01-08 09:24:59
 * 
 * 
 * 修改标识： Author
 * 修改描述： 相关描述
 * 
 * ---------------------------------------------------------------- */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Common.Extensions.OrderBy
{

    /// <summary>
    /// 排序
    /// </summary>
    public  class OrderByExpression<TEntity, TOrderBy> : IOrderByExpression<TEntity> where TEntity : class
    {

        /// <summary>
        /// 排序字段
        /// </summary>
        private readonly Expression<Func<TEntity, TOrderBy>> expression;


        /// <summary>
        /// 是否降序
        /// </summary>
        private readonly bool descending;


        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="expression">字段</param>
        /// <param name="descending">是否降序</param>
        public OrderByExpression(Expression<Func<TEntity, TOrderBy>> expression,
            bool descending = false)
        {
            this.expression = expression;
            this.descending = descending;
        }


        /// <summary>
        /// 第一字段排序
        /// </summary>
        /// <param name="query">IQueryable</param>
        /// <returns>IOrderedQueryable</returns>
        public IOrderedQueryable<TEntity> ApplyOrderBy(
            IQueryable<TEntity> query)
        {
            if (descending)
            {
                return query.OrderByDescending(expression);
            }
            else
            {
                return query.OrderBy(expression);
            }
        }



        /// <summary>
        /// 第二字段及后续字段排序
        /// </summary>
        /// <param name="query">IQueryable</param>
        /// <returns>IOrderedQueryable</returns>
        public IOrderedQueryable<TEntity> ApplyThenBy(
            IOrderedQueryable<TEntity> query)
        {
            if (descending)
            {
                return query.ThenByDescending(expression);
            }
            else
            {
                return query.ThenBy(expression);
            }
        }



    }

}